package vtt.android.dapanhc.activities;

import java.util.Date;

import vtt.android.dapanhc.Constants;
import vtt.android.dapanhc.MyBroadcastReceiver;
import vtt.android.dapanhc.R;
import vtt.android.dapanhc.activities.fragments.TopChallengeFragment;
import vtt.android.dapanhc.activities.fragments.TopMenuFragment;
import vtt.android.dapanhc.basegameutils.BaseGameActivity;
import vtt.android.dapanhc.database.AnswerDAO;
import vtt.android.dapanhc.dialogs.DialogManager;
import vtt.android.dapanhc.dialogs.DialogManager.IDialogListener;
import vtt.android.dapanhc.utils.SntpClient;
import vtt.android.dapanhc.utils.VttAlarmManager;
import vtt.android.library.VttBaseApplication;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.leaderboard.Leaderboards;
import com.google.android.gms.games.leaderboard.Leaderboards.SubmitScoreResult;

public class TopActivity extends BaseGameActivity implements 
			TopMenuFragment.Listener, 
			TopChallengeFragment.Listener,
			IDialogListener {
	
	private static final String DIALOG_CONFIRM_CHALLENGE = "DIALOG_CONFIRM_CHALLENGE";
	private static final String DIALOG_CONFIRM_PRACTICE = "DIALOG_CONFIRM_PRACTICE";
	private static final int MAX_SCORE = 1150;

	// request codes we use when invoking an external activity
    final int RC_RESOLVE = 5000, RC_UNUSED = 5001;
    
	private TopMenuFragment topMenuFragment;
	private TopChallengeFragment topChallengeFragment;

	private DialogManager dialogManager;
	
	private AudioManager audio;

	private AnswerDAO answerDAO;
	
	public SharedPreferences sharedPreferences;
	
	public boolean isNewDay = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		 // enable debug log, if applicable
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_top);
		
		audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		sharedPreferences = getSharedPreferences(Constants.SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
		
		// init database
		answerDAO = AnswerDAO.getInstance(this);
		answerDAO.open();
		
		dialogManager = new DialogManager(this);
		dialogManager.addDialogListener(this);
		
		if(!VttUtils.checkNetworkConnection(mContext)){
			dialogManager.showAlertDialog(Constants.DIALOG_INTERNET_ALERT, "", getString(R.string.msg_network_error), false);
		}
		
		topMenuFragment = new TopMenuFragment();
		topMenuFragment.setListener(this);
		
		topChallengeFragment = new TopChallengeFragment();
		topChallengeFragment.setListener(this);
		// add initial fragment (welcome fragment)
        getSupportFragmentManager()
        		.beginTransaction()
        		.add(R.id.fragment_container, topMenuFragment)
        		.commit();
        
        // check whether show notification
		boolean isStartAlarm = sharedPreferences.getBoolean(Constants.KEY_IS_START_ALARM, false);
		if (!isStartAlarm) {
			int hour = sharedPreferences.getInt(Constants.SHARE_KEY_NOTICE_HOUR, 0);
			// set repeat alarm everyday for showing notification
			// startAlarm(this);
			VttAlarmManager.startAlarmEveryday(mContext, hour, MyBroadcastReceiver.class);
			sharedPreferences.edit().putBoolean(Constants.KEY_IS_START_ALARM, true).commit();
		}
	}
	
	protected void getCurrentNetworkTime() {
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				SntpClient client = new SntpClient();
				log.d("VTT>>> client.requestTime " + client.requestTime("0.ubuntu.pool.ntp.org",6000) );
				if (client.requestTime("0.ubuntu.pool.ntp.org",6000)) {
				    long now = client.getNtpTime() + SystemClock.elapsedRealtime() - 
				    client.getNtpTimeReference();
				    Date current = new Date(now);
				    log.d("VTT>>> " + current.toString());
				}
			}
		}).start();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		answerDAO.close();
	}
	
	public boolean isPracticed() {
		// check whether day is new
		boolean flg = sharedPreferences.getBoolean(Constants.SHARE_KEY_IS_PRACTICED, false);
		log.d("VTT>>> isPracticed " + flg);
		return flg;
	}
	
	// Switch UI to the given fragment
    public void switchToFragment(Fragment newFrag) {
        getSupportFragmentManager().beginTransaction()
        	.replace(R.id.fragment_container, newFrag)
        	.addToBackStack(newFrag.getClass().getSimpleName())
        	.commit();
    }

	@Override
	public void onSignInFailed() {
		// Sign in has failed. So show the user the sign-in button.
	}

	@Override
	public void onSignInSucceeded() {
		// show sign-out button, hide the sign-in button
	}

	@Override
	public void onStartChallenge() {
		
		VttGA.sendEvent(this,"onStartChallenge", "onStartChallenge", null, 0);
		
		/*if(isPracticed()){
			Toast toast = Toast.makeText(mContext, R.string.msg_waiting_until_tomorrow, 0);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}*/
		
		if (!isSignedIn() && !VttBaseApplication.isDebuggable) { // check debuggable for testing
		//if (!isSignedIn()) {
			beginUserInitiatedSignIn();
		} else {
			dialogManager.showAlertDialog(DIALOG_CONFIRM_CHALLENGE, 
					getString(R.string.msg_title_notice), 
					String.format(getString(R.string.msg_challenge_notice), Constants.NUMBER_TIME_CHALLENGE / 60), // message
					true);
		}
		
	}

	@Override
	public void onPracticeRequested() {
		
		VttGA.sendEvent(this, "onPracticeRequested", "onPracticeRequested", null, 0);
		
		/*if(!isPracticed()){
			dialogManager.showAlertDialog(DIALOG_CONFIRM_PRACTICE, 
					getString(R.string.msg_title_notice), 
					getString(R.string.msg_practice_notice),
					true);
		} else {
			// start practice screen
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}*/
		
		Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
	}

	@Override
	public void onShowAchievementsRequested() {
		if (isSignedIn()) {
			startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), RC_UNUSED);
        } else {
            //showAlert(getString(R.string.msg_please_sign_in));
        	beginUserInitiatedSignIn();
        }
	}

	@Override
	public void onShowLeaderboardsRequested() {
		
		VttGA.sendEvent(this, "onShowLeader", "onShowLeader", null, 0);
		
		if (isSignedIn()) {
			startActivityForResult(
					Games.Leaderboards.getLeaderboardIntent(getApiClient(),getString(R.string.leaderboard_english_master)), 
					RC_UNUSED);
		} else {
			//showAlert(getString(R.string.msg_please_sign_in));
			beginUserInitiatedSignIn();
		}
	}

	@Override
	public void onSignInButtonClicked() {
		// start the asynchronous sign in flow
		beginUserInitiatedSignIn();
	}

	@Override
	public void onSignOutButtonClicked() {
		// sign out.
		signOut();
	}

	@Override
	public void onSubmitScore(int score) {
		log.d("VTT>>> SubmitScore " + score);
		// prevent cheat
		if(score < MAX_SCORE){
			try {
				if (isSignedIn()) {
					//Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_english_master), score);
					PendingResult<SubmitScoreResult> submitScoreImmediate = Games.Leaderboards.submitScoreImmediate(getApiClient(), getString(R.string.leaderboard_english_master), score);
					submitScoreImmediate.setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
						
						@Override
						public void onResult(SubmitScoreResult  result) {
							log.d("VTT>>> onResult SubmitScoreResult " + result.getStatus());
							log.d("VTT>>> onResult SubmitScoreResult " + result.getScoreData().toString());
						}
					});
					
					VttGA.sendEvent(this, "onSubmitScore", "onSubmitScore", "" + score, 0);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onOkClick(String dialogName) {
		
		if(Constants.DIALOG_INTERNET_ALERT.equals(dialogName)){
			//finish();
		}
		
		if (DIALOG_CONFIRM_CHALLENGE.equals(dialogName)) {
			switchToFragment(topChallengeFragment);
		} else if(DIALOG_CONFIRM_PRACTICE.equals(dialogName)){
			// assign 
			sharedPreferences.edit().putBoolean(Constants.SHARE_KEY_IS_PRACTICED, true).commit();
			
			// start practice screen
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void onCancelClick(String dialogName) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onViewLeaderBoardClick(String dialogName) {
		getSupportFragmentManager().beginTransaction().remove(topChallengeFragment);
		switchToFragment(topChallengeFragment);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_UP:
			audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
			return true;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
			return true;
		default:
			return super.onKeyDown(keyCode, event);
		}
	}
}
